package lvbu.wang.lvbuoperator.ui.scan;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.qing.library.utils.StringUtil;
import com.qing.library.widget.CustomProgress;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import lvbu.wang.lvbuoperator.R;
import lvbu.wang.lvbuoperator.adapter.BluetoothListAdapter;
import lvbu.wang.lvbuoperator.bean.BleMotorInfo;
import lvbu.wang.lvbuoperator.bean.BluetoothInfoBean;
import lvbu.wang.lvbuoperator.bean.ScanRecord;
import lvbu.wang.lvbuoperator.bean.SendCommandResult;
import lvbu.wang.lvbuoperator.constants.ConstantsValue;
import lvbu.wang.lvbuoperator.constants.RouteConstant;
import lvbu.wang.lvbuoperator.core.App;
import lvbu.wang.lvbuoperator.core.BaseActivity;
import lvbu.wang.lvbuoperator.http.BleHttpHelp;
import lvbu.wang.lvbuoperator.manager.ThreadPool;
import lvbu.wang.lvbuoperator.services.BluetoothLEService;
import lvbu.wang.lvbuoperator.function.nologin.NoLoginOperationActivity;
import lvbu.wang.lvbuoperator.ui.debug.BleLocalDebugActivity;
import lvbu.wang.lvbuoperator.ui.paramset.ui.BleParamSetActivity;
import lvbu.wang.lvbuoperator.utils.CommandUtils;
import lvbu.wang.lvbuoperator.utils.CommonUtil;
import lvbu.wang.lvbuoperator.utils.FormatUtil;
import lvbu.wang.lvbuoperator.utils.StringHelper;
import lvbu.wang.lvbuoperator.widget.CustDialog;


/**
 * Created by DaiQing.Zha on 2016/11/3 0003.
 */
public class BleBluetoothListActivity extends BaseActivity {

    private static final int REQUEST_ENABLE_BT = 1;
    private static final long SCAN_PERIOD = 30 * 1000;  //10秒后停止查找搜索.
    private ListView mLstBluetooth;
    private List<String> mLstAddress;
    private ImageView mImgRefresh;
    private TextView mTvScan;
    private CustomProgress mCustomProgress;  //自定义进度条
    private BluetoothListAdapter mLeDeviceListAdapter;
    private List<BluetoothInfoBean> mBluetoothInfoBeanList;
    private BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning = false;
    private Handler mHandler;
    Animation mOperatingAnim;
    LinearInterpolator mLinearInterpolator;
    private boolean mIsOnShow = true;    //当前页面是否正在显示
    private BluetoothAdapter.LeScanCallback mLeScanCallback;
    private Dialog mDialog;
    private boolean isActivityShow = false;
    private String mOperationType = "";//操作类型---用于蓝牙页面区分蓝牙连接成功后是跳转到参数设置界面,还是跳转到免登陆界面或者本地调试界面

    /**
     * 定义广播接收器，接收蓝牙消息
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            if (intent.getAction().equals(ConstantsValue.ACTION_BLUETOOTH_CONNECT_STATE_CHANGED)) { //蓝牙状态改变
                if (BaseActivity.getMotorDefault_bluetooth_connect_state(BleBluetoothListActivity.this) == BluetoothLEService.Bluetooth_CONNECTED){
                    Log.e("mainASDFGHJKL","showDialog");
                    mCustomProgress.dissMiss();
                    if (!mDialog.isShowing() && isActivityShow){
                        mDialog.show();
                    }
                }
                if (BaseActivity.getMotorDefault_bluetooth_connect_state(BleBluetoothListActivity.this) == BluetoothLEService.Bluetooth_UNCONNECT){
                    if (mIsOnShow){
                        mCustomProgress.dissMiss();
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        if (intent != null) {
            mOperationType = intent.getStringExtra(ConstantsValue.OPERATION_TYPE);
        }
        setContentView(R.layout.activity_bluetooth_list);
        final View view = LayoutInflater.from(BleBluetoothListActivity.this).inflate(R.layout.view_of_confirm_connected,null);
        CustDialog.Builder builder = new CustDialog.Builder(BleBluetoothListActivity.this, view);
        builder.setOKDialogButton(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Log.e("mainNewProtocolHHZY","获取信息");
                initMotorInfo();
                Log.e("mainBLEINFO","disShowDialog");
            }
        });
        builder.setCancelDialogButton(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                BluetoothLEService.disConnect();
            }
        });
        mDialog = builder.create();
        mDialog.setCancelable(false);
        registerBroadcast();
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void init() {
        mBluetoothInfoBeanList = new ArrayList<>();
        mLstAddress = new ArrayList<>();
        mCustomProgress = new CustomProgress(this);
        mLstBluetooth = findView(R.id.lst_bluetooth);
        mImgRefresh = findView(R.id.img_refresh);
        mTvScan = findView(R.id.tv_scan);
        mHandler = new Handler();
        mLinearInterpolator = new LinearInterpolator();
        mOperatingAnim = AnimationUtils.loadAnimation(this, R.anim.rotate_scan);
        mOperatingAnim.setInterpolator(mLinearInterpolator);
        // 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            showToastMsg(getString(R.string.toast_comm_bleNotSupported));
            finish();
        }

        // 初始化 Bluetooth adapter, 通过蓝牙管理器得到一个参考蓝牙适配器(API必须在以上android4.3或以上和版本)
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        // 检查设备上是否支持蓝牙
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.toast_comm_errorBluetoothNotSupported, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        mImgRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mScanning){ //正在扫描
                    scanLeDevice(false);
                }else{
                    mLstAddress.clear();
                    mBluetoothInfoBeanList.clear();
                    mLeDeviceListAdapter.notifyDataSetChanged();
                    scanLeDevice(true);
                }
            }
        });
        mLstBluetooth.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BaseActivity.saveMotorDefault_bluetooth_connect_state(BleBluetoothListActivity.this, BluetoothLEService.Bluetooth_UNCONNECT);    //设置蓝牙状态为已连接
                String selectedAddress = mBluetoothInfoBeanList.get(position).getAddress();
                BleMotorInfo bleMotorInfo = App.getInstance().getBleMotorInfo();
                String motorName = mBluetoothInfoBeanList.get(position).getName();
                bleMotorInfo.setBluetoothAddress(selectedAddress);
                bleMotorInfo.setMotorName(motorName);
                App.getInstance().setBikeMotor(bleMotorInfo);
                setBluetoothAddress(BleBluetoothListActivity.this,selectedAddress);
                BluetoothLEService.connect();
                scanLeDevice(false);
                Log.e("mainNewProtocolHHZY","正在连接蓝牙");
//                mCustomProgress.show(BleBluetoothListActivity.this,"正在连接蓝牙",false,null);
                mCustomProgress.show(BleBluetoothListActivity.this, "正在连接蓝牙", false, null, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CustomProgress.dissMiss();
                        BluetoothLEService.disConnect();
                    }
                });
            }
        });

        mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

            @Override
            public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ScanRecord scanRecord1 = parseScanRecord(scanRecord);
                        if (mLstAddress.contains(device.getAddress())){
                            for (int i = 0; i < mBluetoothInfoBeanList.size(); i ++){   //如果该蓝牙在列表中已经存在，我们只需要更新它的蓝牙信号强度就ok了
                                if (mBluetoothInfoBeanList.get(i).getAddress().equals(device.getAddress())) {
                                    mBluetoothInfoBeanList.get(i).setRssi(rssi + "");
                                }
                            }
                        }else if (ConstantsValue.LOCAL_NAME.equalsIgnoreCase(scanRecord1.getLocalName())){
                            BluetoothInfoBean bluetoothInfoBean = new BluetoothInfoBean();
                            bluetoothInfoBean.setAddress(device.getAddress().toUpperCase());
                            bluetoothInfoBean.setRssi(rssi + "");
                            bluetoothInfoBean.setName(scanRecord1.getDeviceName());
                            mLstAddress.add(device.getAddress());
                            mBluetoothInfoBeanList.add(bluetoothInfoBean);
                        }
                        mLeDeviceListAdapter.notifyDataSetChanged();
                    }
                });
            }
        };
        getSupportActionBar().setTitle(getString(R.string.app_ble_name));
    }

    //    长度，字段，值
    //    02 01 06 可连接性
    //    0B FF 4C764275 38D269FEDE40 制造商 + 蓝牙地址
    //    03 02 E0FF uuid
    //    0A 09 4C7642754D6F746F72	local name
    //    0B 16 002A 616263032A616263  service data device name
    //    0000000000000000000000000000000000000000
    //    0201060BFF4C76427538D269FEDE400302E0FF0A094C7642754D6F746F720B16002A616263032A6162630000000000000000000000000000000000000000
    /**
     * 解析scanRecord
     * @param scanRecord
     * @return
     */
    private ScanRecord parseScanRecord(byte[] scanRecord){
        ScanRecord scanRecordBean = new ScanRecord();
        int startNum = 0;   //数组开始位置
        int num = scanRecord[0]; //数组元素个数
        for (int i = 0; i < scanRecord.length;i = startNum){
            byte[] value = Arrays.copyOfRange(scanRecord, startNum, startNum + num + 1);
            startNum = startNum + num + 1;
            num = scanRecord[startNum];
            if ("00".equals(StringUtil.bytesToHexString(value))) break;
            switch (value[1]){
                case 0x01:  //可连接性
                    break;
                case (byte) 0xFF:   //制造商 + 蓝牙地址
                    break;
                case 0x02:  //uuid
                    break;
                case 0x09:  //local name
                    scanRecordBean.setLocalName(new String(Arrays.copyOfRange(value,2,value.length)));
                    break;
                case 0x16:  //service data + device name
                    scanRecordBean.setDeviceName(new String(Arrays.copyOfRange(value,4,value.length)));
                    break;
            }
        }
        return scanRecordBean;
    }

    /**
     * 初始化电机信息
     */
    private void initMotorInfo(){
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                String[] commandHeads = {"BA","BB","AC","A5","A6","AB"   //硬件版本,固件版本,蓝牙地址,助力等级,超速报警，轮胎周长
                        ,"AE","AF","C3","C4","D2"   //车重,载重,电机状态,助力模式,上坡助力角度
                        ,"D3","D1","D0"};    //上坡助力等级,电池功率,电池型号,电机系列
                StringBuffer sendCodeBuf = new StringBuffer();
                for (int i = 0; i < commandHeads.length; i ++){
                    sendCodeBuf.append(commandHeads[i]);
                }
                String sendCode = sendCodeBuf.toString();
                sendCode = CommandUtils.FLAG_GET + sendCode;
                SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, CommandUtils.getInquireCommand(commandHeads));
                Log.e("mainNewProtocolHH","sendCode1 " + sendCodeBuf + " sendCodeMM1 = " + CommandUtils.getInquireCommand(commandHeads) + " scr1 = " + scr.toString());
                if (scr.isResult()) {
                    try{
                        String answerResult = StringHelper.subString(scr.getAnswerContent(),6,8);
                        if ("01".equals(answerResult)){
                            BleMotorInfo bleMotorInfo = App.getInstance().getBleMotorInfo();
                            HashMap map = CommandUtils.getInquireMap(scr.getAnswerContent());
                            Set set1 = map.keySet();
                            for (Object obj : set1) {
                                if (obj.equals("BA")){  //硬件版本
                                    bleMotorInfo.setHardwareVersion(String.valueOf(map.get(obj)));
                                    Log.e("mainNewProtocolHH","hardWareVersion = " + String.valueOf(map.get(obj)));
                                }
                                if (obj.equals("BB")){  //固件版本
                                    bleMotorInfo.setFirmwareVersion(String.valueOf(map.get(obj)));
                                }
                                if (obj.equals("AC")){  //蓝牙地址
                                    bleMotorInfo.setBluetoothAddress(CommonUtil.convertBluetoothAddress(String.valueOf(map.get(obj))));
                                }
                                if (obj.equals("A5")){  //助力等级
                                    bleMotorInfo.setPowerLevel(Integer.parseInt(String.valueOf(map.get(obj)),16));   //助力等级
                                    Log.e("mainNewProtocolHH","powerLevel = " + Integer.valueOf(String.valueOf(map.get(obj)),16));
                                }
                                if (obj.equals("A6")){  //超速报警
                                    bleMotorInfo.setSpeedLimitValue(Integer.parseInt(String.valueOf(map.get(obj)),16));   //助力等级
                                    Log.e("mainNewProtocolHH","speedLimit = " + Integer.valueOf(String.valueOf(map.get(obj)),16));
                                }
                                if (obj.equals("AB")){  //轮胎周长
                                    bleMotorInfo.setCircumference(FormatUtil.str2Float(String.valueOf(map.get(obj)),3));
                                }
                                if (obj.equals("AE")){  //车重
                                    bleMotorInfo.setBikeWeight((float) Integer.parseInt(String.valueOf(map.get(obj)),16));
                                }
                                if (obj.equals("AF")){  //载重
                                    bleMotorInfo.setLoadWeight((float) Integer.parseInt(String.valueOf(map.get(obj)),16));
                                }
                                if (obj.equals("C3")){  //电机状态
                                    bleMotorInfo.setStatusCode(String.valueOf(map.get(obj)));
                                }
                                if (obj.equals("C4")){  //助力模式
                                    bleMotorInfo.setAssistantMode(String.valueOf(map.get(obj)));
                                }
                                if (obj.equals("D2")){  //上坡助力角度
                                    bleMotorInfo.setUpHillAngle(FormatUtil.str2Float(String.valueOf(map.get(obj)),1));
                                }
                                if (obj.equals("D3")){  //上坡助力等级
                                    bleMotorInfo.setUpHillPowerLevel(Integer.parseInt(String.valueOf(map.get(obj)),16));
                                }
                                if (obj.equals("D1")){  //电池功率
                                    Log.e("mainNewProtocolHHQ","D1 = " + map.get(obj));
                                    bleMotorInfo.setBatteryRate(Integer.parseInt(String.valueOf(map.get(obj)),16));   //电池功率数
                                }
                                if (obj.equals("D0")){  //电机系列
                                    bleMotorInfo.setMotorSeries(StringUtil.string2Ascii(String.valueOf(map.get(obj))));
                                    Log.e("mainNewProtocolHH","D0 = " + StringUtil.string2Ascii(String.valueOf(map.get(obj))));  
                                }
                            }
                            App.getInstance().setBikeMotor(bleMotorInfo);
                            Map<String, Object> queryStrings = new HashMap<>();
                            queryStrings.put("bluetoothAddress", bleMotorInfo.getBluetoothAddress());
                            queryStrings.put("hardwareVersion", bleMotorInfo.getHardwareVersion());
                            queryStrings.put("firmwareVersion", bleMotorInfo.getFirmwareVersion());
                            String source = BleHttpHelp.getData(RouteConstant.SET_MOTOR_INFO_VERSION_UPDATE, queryStrings, true, BleBluetoothListActivity.this);
                            Log.e("mainASDFGHJZY","---source--- = " + source);
                            Log.e("mainASDFGHJZY","---bleMotorInfo--- = " + bleMotorInfo.toString());
                            if ("success".equals(source.replace("\"",""))){
                                BluetoothLEService.disConnect();
                                if (mDialog.isShowing()) mDialog.dismiss();
                                if (ConstantsValue.OPERATION_TYPE_NO_LOGIN.equals(mOperationType)) {
                                    startActivity(new Intent(BleBluetoothListActivity.this,NoLoginOperationActivity.class));
                                } else if (ConstantsValue.OPERATION_TYPE_LOCAL_DEBUG.equals(mOperationType)) {
                                    startActivity(new Intent(BleBluetoothListActivity.this, BleLocalDebugActivity.class));
                                } else {
                                    startActivity(new Intent(BleBluetoothListActivity.this,BleParamSetActivity.class));
                                }
                            }else{
                                BluetoothLEService.disConnect();
                                showToastMsg(source);
                            }
                        }else{
                            //TODO:返回不是01
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showToastMsg("获取数据失败！");
                                }
                            });
                        }
                    }catch (Exception e){
                        Log.e("mainNewProtocolHH = ","error error = " + e.toString());
                    }
                } else {
                    //TODO:应答失败
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showToastMsg("获取数据失败！");
                        }
                    });
                }
            }
        });
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
                @Override
                public void run() {
                    mScanning = false;
                    mImgRefresh.clearAnimation();
                    mTvScan.setText(getString(R.string.bluetoothList_scan));
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    invalidateOptionsMenu();
                }
            }, SCAN_PERIOD);

            mScanning = true;
            mImgRefresh.startAnimation(mOperatingAnim);
            mTvScan.setText(getString(R.string.bluetoothList_stop));
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            mImgRefresh.clearAnimation();
            mTvScan.setText(getString(R.string.bluetoothList_scan));
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        invalidateOptionsMenu();
    }
    /**
     * 注册广播接收器
     */
    private void registerBroadcast(){
        IntentFilter filter;
        filter = new IntentFilter();
        filter.addAction(ConstantsValue.ACTION_BLUETOOTH_CONNECT_STATE_CHANGED);
        this.registerReceiver(broadcastReceiver, filter);
    }

    /**
     * 解除广播注册
     */
    private void unRegisterBroadcast(){
        unregisterReceiver(broadcastReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsOnShow = true;
        // 为了确保设备上蓝牙能使用, 如果当前蓝牙设备没启用,弹出对话框向用户要求授予权限来启用
        if (!mBluetoothAdapter.isEnabled()) {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }
        // Initializes list view adapter.
        mLeDeviceListAdapter = new BluetoothListAdapter(this, mBluetoothInfoBeanList);
        mLstBluetooth.setAdapter(mLeDeviceListAdapter);
        isActivityShow = true;
        scanLeDevice(true);
    }
    @Override
    protected void onPause() {
        super.onPause();
        mIsOnShow = false;
        mLstAddress.clear();
        mBluetoothInfoBeanList.clear();
        isActivityShow = false;
        scanLeDevice(false);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterBroadcast();
    }
}
